/*
 * @lc app=leetcode.cn id=224 lang=golang
 * @lcpr version=30118
 *
 * [224] 基本计算器
 */

// @lcpr-template-start
package main

import "fmt"

func main() {
	fmt.Println(calculate("(1+(4+5+2)-3)+(6+8)"))
}

// @lcpr-template-end
// @lc code=start

func calculate(s string) int {
	res, _ := dfs(s, 0)
	return res
}

func dfs(s string, start int) (int, int) {
	sign := 1
	res := 0
	for i := start; i < len(s); i++ {
		switch s[i] {
		case ' ':
			continue
		case '+':
			sign = 1
		case '-':
			sign = -1
		case '(':
			num, right := dfs(s, i+1)
			res = res + sign*num
			i = right
		case ')':
			return res, i

		default:
			num := 0
			for ; i < len(s) && s[i] >= '0' && s[i] <= '9'; i++ {
				num = num*10 + int(s[i]-'0')
			}
			i--
			res = res + sign*num
		}
	}
	return res, len(s)
}

// @lc code=end

/*
// @lcpr case=start
// "1 + 1"\n
// @lcpr case=end

// @lcpr case=start
// " 2-1 + 2 "\n
// @lcpr case=end

// @lcpr case=start
// "(1+(4+5+2)-3)+(6+8)"\n
// @lcpr case=end

*/
